import { _decorator, Component, director, Node } from 'cc';
import { CatAction } from './CatAction';
import { PinAction } from './PinAction';
import { ColorDate } from './ColorDate';
import { events } from './Enums';
const { ccclass, property } = _decorator;

@ccclass('LayerCatAction')
export class LayerCatAction extends Component {

    onLoad() {
        director.on(events.check_empty_hole, this.check_empty_hole, this);
    }

    // put a pin to slot by pin_color
    public put_pin(pin: PinAction): boolean {
        const target = this.preput_to_cat(pin);
        if (target) {
            return target.put_pin(pin);
        }
        return false;
    }

    // 查找可以放置pin的CatAction，优先空洞最少的
    public preput_to_cat(pin: PinAction): CatAction | null {
        const canMoveArr: CatAction[] = [];

        for (const slot of this.node.children) {
            const catAction = slot.getComponent(CatAction);
            if (catAction?.check_able_put(pin)) {
                canMoveArr.push(catAction);
            }
        }

        if (canMoveArr.length === 0) return null;

        // 找空洞数最少的CatAction
        return canMoveArr.reduce((prev, curr) => {
            return curr.get_temp_hole_num() < prev.get_temp_hole_num() ? curr : prev;
        });
    }

    // 初始化所有子节点的 CatAction
    public init_cat() {
        for (const slot of this.node.children) {
            slot.getComponent(CatAction)?.init_cat();
        }
    }

    // 获取所有子节点 CatAction 的颜色数组
    public get_cat_color_arr(): ColorDate[] {
        const arr: ColorDate[] = [];
        for (const slot of this.node.children) {
            const catAction = slot.getComponent(CatAction);
            if (catAction) {
                const color = catAction.get_cat_color();
                if (color) arr.push(color);
            }
        }
        return arr;
    }

    // 获取所有被锁定的 Cat 节点
    public get_locked_cat(): Node[] {
        const arr: Node[] = [];
        for (const catNode of this.node.children) {
            const catAction = catNode.getComponent(CatAction);
            if (catAction?.isLocked) {
                arr.push(catNode);
            }
        }
        return arr;
    }

    // 事件响应，检测空洞并加载pin
    check_empty_hole(pin: PinAction) {
        const cat = this.preput_to_cat(pin);
        if (cat) {
            console.log("收到消息，放入数据...");
            cat.load_pin();
        }
    }
}
